<script setup lang="ts">
import {ref, onMounted, inject, type Ref} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import { getCurrentInstance } from 'vue';
import { ArrowLeft } from '@element-plus/icons-vue';

// 路由参数
const route = useRoute();
const currentUserId = Number(route.params.currentUserId); // 当前用户ID
const otherUserId = Number(route.params.otherUserId); // 对方用户ID

// 全局属性
const global = getCurrentInstance()?.appContext.config.globalProperties;

// 状态管理
const chatRecords = ref<any[]>([]); // 聊天记录
const newMessage = ref(''); // 新消息内容
const loading = ref(false);
const otherUserInfo = ref({ username: '', avatar: '', id: null });

// 获取聊天记录
const getChatRecords = async () => {
  loading.value = true;
  try {
    const resp = await global.$http.get('/backend/chatRecords', {
      params: { senderId: currentUserId, receiverId: otherUserId }
    });
    if (resp.data && Array.isArray(resp.data)) {
      // 按时间升序排序
      chatRecords.value = resp.data.sort(
          (a: any, b: any) => new Date(a.sendTime).getTime() - new Date(b.sendTime).getTime()
      );
    }
  } catch (err) {
    ElMessage.error('加载聊天记录失败');
  } finally {
    loading.value = false;
  }
};

// 获取对方用户信息
const getOtherUserInfo = () => {
  if (chatRecords.value.length === 0) return;

  // 遍历所有消息的 userList ，找到 id 等于 otherUserId 的用户（路由中明确的对方ID）
  for (const msg of chatRecords.value) {
    if (msg.userList && msg.userList.length > 0) {
      const user = msg.userList.find((u: any) => u.id === otherUserId);
      if (user) {
        otherUserInfo.value = user; // 匹配对方 ID
        return; // 找到后退出循环
      }
    }
  }

  // 未找到
  otherUserInfo.value = {
    id: otherUserId,
    username: `用户${otherUserId}`,
    avatar: `https://picsum.photos/seed/${otherUserId}/200/200`
  };
};

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return;
  try {
    const sendTime = getStandardTime();
    console.log("前端发送的时间：", sendTime);
    await global.$http.post('/backend/chat', {
      senderId: currentUserId,
      receiverId: otherUserId,
      messageContent: newMessage.value,
      sendTime: sendTime
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    newMessage.value = '';
    await getChatRecords(); // 重新获取记录后，自动更新对方信息
    getOtherUserInfo(); // 确保新消息后信息同步
  } catch (err) {
    ElMessage.error('发送失败');
  }
};

// 格式化时间为 "yyyy-MM-dd HH:mm:ss"
const getStandardTime = () => {
  const date = new Date();
  // 提取年、月、日
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
  const day = String(date.getDate()).padStart(2, '0');
  // 提取时、分、秒
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  // 拼接为标准格式
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取头像
const getAvatarUrl = (userId: number) => {
  // 遍历所有消息，找到该用户的信息
  for (const msg of chatRecords.value) {
    if (msg.userList && msg.userList.length > 0) {
      const user = msg.userList.find((u: any) => u.id === userId);
      if (user && user.avatar) {
        return user.avatar; // 返回该用户的头像
      }
    }
  }
  // 无头像
  return `https://picsum.photos/seed/${userId}/200/200`;
};

const getAvatarText = (userId: number) => {
  return userId === currentUserId
      ? currentUser.value?.username?.[0] || '我'
      : otherUserInfo.value.username?.[0] || 'U';
};

const formatTime = (time: string) => {
  const date = new Date(time);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 注入当前用户信息（复用全局状态）
const currentUser = inject<Ref<any>>('userState');

// 初始化逻辑调整：先获取聊天记录，再从记录中提取对方信息
onMounted(async () => {
  await getChatRecords(); // 先获取聊天记录
  getOtherUserInfo(); // 再从记录中提取对方信息（依赖聊天记录）
});

</script>

<template>
  <div class="chatbox">
    <!-- 顶部导航 -->
    <div class="chat-header">
      <el-button type="text" @click="$router.back()">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <div class="name">{{ otherUserInfo.username || `用户${otherUserId}` }}</div>
    </div>

    <!-- 消息区域 -->
    <div class="messages-container">
      <!-- 加载状态 -->
      <el-loading v-if="loading" fullscreen />

      <!-- 消息列表（按时间排序） -->
      <div
          v-for="(msg, index) in chatRecords"
          :key="index"
          :class="['message-item', msg.userList[0].id === currentUserId ? 'sent' : 'received']"
      >
        <!-- 头像 -->
        <el-avatar
            :src="getAvatarUrl(msg.userList[0].id)"
            :text="getAvatarText(msg.userList[0].id)"
            class="avatar"
        ></el-avatar>

        <!-- 消息内容 -->
        <div class="message-content">
          <span class="time">{{ formatTime(msg.sendTime) }}</span>
          <p>{{ msg.messageContent }}</p>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
          v-model="newMessage"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
      ></el-input>
      <el-button @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<style scoped>
.chatbox {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding-bottom: 60px; /* 留出底部输入区域空间 */
}

.chat-header {
  display: flex;
  height: 40px;
  align-items: center;
}

.name{
  margin-left: 120px;
}

.messages-container {
  flex: 1;
  padding: 2px;
  overflow-y: auto;
  background: #f5f5f5;
}

.message-item {
  display: flex;
  margin: 10px 0;
  max-width: 80%;
}

.sent {
  flex-direction: row-reverse;
  margin-left: auto;
}

.received {
  margin-right: auto;
}

.avatar {
  width: 40px;
  height: 40px;
  margin: 0 10px;
}

.message-content {
  padding: 5px 5px;
  border-radius: 8px;
  position: relative;
}

/* 自己的消息样式 */
.sent .message-content {
  background: #409eff;
  color: white;
}

/* 对方的消息样式 */
.received .message-content {
  background: #fff;
  border: 1px solid #eee;
}

.time {
  font-size: 12px;
  opacity: 0.8;
  margin-top: 5px;
  display: inline-block;
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 10px;
  border-top: 1px solid #eee;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.input-area el-input {
  flex: 1;
}
</style>